package com.owen.springsecuritydemo.service.impl;

import com.owen.springsecuritydemo.domain.LoginUser;
import com.owen.springsecuritydemo.domain.ResponseResult;
import com.owen.springsecuritydemo.domain.User;
import com.owen.springsecuritydemo.service.LoginService;
import com.owen.springsecuritydemo.utils.JwtUtil;
import com.owen.springsecuritydemo.utils.RedisCache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {


    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;



    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());



        //AuthenticationManager authenticate进行用户认证
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);


        //如果认证没有通过，给出对应提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名密码错误");
        }

        //如果认证通过了，使用userid生成一个jwt

        //把完整的用户信息存入redis

        //如果认证通过，就使用userid生成一个jwt，然后把jwt存入ResponseResult后返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);

        //把完整的用户信息存入redis，其中userid作为key，注意存入redis的时候加了前缀 login:
        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);
        redisCache.setCacheObject("login:"+userid,loginUser);
        return new ResponseResult(200,"登录成功",map);

    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) usernamePasswordAuthenticationToken.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult<>(200,"注销成功");
    }
}
